<template lang="pug">
  .CreateAccountModal
    Modal(
      v-model="isShowCreateEnterpriseCertificateModal"
      :title="createEnterpriseCertificateModalTitle"
      class-name="vertical-center-modal"
      width="780"
    )
      Form.ivu-row.pr-20(ref="formData" :model="formData" :rules="rules" :label-width="140")
        FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'input'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled")
          template(v-if="item.type === 'select'")
            Select(v-model="formData[item.model]" :placeholder="item.placeholder" filterable)
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.label") {{c_item.label}}
          template(v-if="item.type === 'switch'")
            i-switch(v-model="formData[item.model]")
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" type="date" @on-change="handleChangeDatePicker(item.model, $event)")
          template(v-if="item.type === 'upload'")
            Row
              Col(span="24")
                Upload(
                  ref="upload"
                  :max-size="10 * 1024"
                  :on-exceeded-size="handleMaxSizeTen"
                  :before-upload="handleBeforeUpload"
                  :on-success="uploadSuccess"
                  :action="baseUrl + 'api/BusinessDocument/PostDocument'"
                  :show-upload-list="false"
                  :data="formData"
                )
                  Input(v-if="file" v-model="file.name" v-show="false")
                  Button(type="info" icon="ios-cloud-upload-outline") 附件上传
              Col(span="24")
                .text-gray-9 仅支持上传10M以内的文件
              Col(span="24" v-if="file")
                .download-btn.display-inline-block.mr-10.relative
                  Button(v-if="file.houzhui === 'jpg' || file.houzhui === 'png' || file.houzhui === 'gif'" size="small" :class="isCanDownload ? 'pr-35' : ''" @click="previewImg(file.path)") {{file.name}}
                  Button.btn-follow-txt(v-else size="small" :class="isCanDownload ? 'pr-35' : ''") {{file.name}}
                  Icon.btn-r-download(v-if="isCanDownload" type="md-download" :class="isCanDownload ? 'r-5' : ''" @click="accessoryDownload(file.path)")

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSubmitBatchImport" :loading="!isCanSubmit") 保存

    //-图片预览
    Modal(title="附件预览" v-model="isPreviewImgModal" footer-hide)
      img(:src="currentPreviewImg")
</template>

<script>
import config from '@/config'
import { Common } from '@/utils/common.js'
import { BusinessDocumentApi } from '@/api/BusinessDocument.api.js'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'CreateEnterpriseCertificateModal',

  watch: {
  },

  computed: {
  },

  data () {
    return {
      baseUrl: baseUrl,
      isShowCreateEnterpriseCertificateModal: false,
      createEnterpriseCertificateModalTitle: '',
      // basicDataId: null,
      formData: {
        id: '',
        documentType: '',
        documentName: '',
        unit: '',
        startTime: '',
        endTime: '',
        location: '',
        leader: '',
        remark: '',
        fileName: ''
      },
      formItem: [
        { type: 'select', label: '证件类别：', placeholder: '请选择证件类别', prop: 'documentType', model: 'documentType', style: 'ivu-col-span-12', options: 'DocumentType' },
        { type: 'input', label: '证件名称：', placeholder: '请输入证件名称', prop: 'documentName', model: 'documentName', style: 'ivu-col-span-12' },
        { type: 'input', label: '办证机构：', placeholder: '请输入办证机构', prop: 'unit', model: 'unit', style: 'ivu-col-span-12' },
        { type: 'datePicker', label: '证件开始时间：', placeholder: '请选择证件开始时间', prop: 'startTime', model: 'startTime', style: 'ivu-col-span-12' },
        { type: 'datePicker', label: '证件结束时间：', placeholder: '请选择证件结束时间', prop: 'endTime', model: 'endTime', style: 'ivu-col-span-12' },
        { type: 'input', label: '储存位置：', placeholder: '请输入储存位置', prop: 'location', model: 'location', style: 'ivu-col-span-12' },
        { type: 'input', label: '负责人：', placeholder: '请输入负责人', prop: 'leader', model: 'leader', style: 'ivu-col-span-12' },
        { type: 'input', label: '备注：', placeholder: '请输入备注', prop: 'remark', model: 'remark', style: 'ivu-col-span-12' },
        { type: 'upload', label: '附件上传：', placeholder: '请上传附件', prop: 'fileName', model: 'fileName', style: 'ivu-col-span-24', files: [] },
      ],
      rules: {
        documentType: [
          { required: true, message: '请选择证件类别'}
        ],
        documentName: [
          { required: true, message: '请输入证件名称'}
        ],
        startTime: [
          { required: true, message: '请选择证件开始时间'}
        ],
        endTime: [
          { required: true, message: '请选择证件结束时间'}
        ]
      },
      arrListDown: {
        defaultOps: [
          { label: '是', value: 'true' },
          { label: '否', value: 'false' }
        ],
        DocumentType: []
      },
      file: null,
      isCanSubmit: true,
      isCanDownload: true,
      isPreviewImgModal: false,
      currentPreviewImg: null
    }
  },

  mounted () {
    this.getEnum()
  },

  methods: {
    // 数据字典
    getEnum () {
      let typeName = 'DocumentType'
      Common.getSelectIdList(typeName, this.arrListDown)
      console.log('this.arrListDown: ', this.arrListDown)
    },

    // 监听所有调用的方法
    listenCall (methodsWords, param) {
      this[methodsWords](param)
    },

    cancel () {
      this.isShowCreateEnterpriseCertificateModal = false
    },

    show () {
      this.formData.id = ''
      this.isCanSubmit = true
      this.isCanDownload = true
      this.isShowCreateEnterpriseCertificateModal = true
      this.file = null
      this.$refs.formData.resetFields()
      console.log('点击是的show()', this.formData)
    },

    // 根据ID获取用户信息
    async getModel (id) {
      console.log('🐟 id: ', id)
      let res = await BusinessDocumentApi.getDocument({ id: id })
      console.log('获取modal res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        if (result.fileName && result.filePath) {
          this.file = {
            name: result.fileName,
            path: result.filePath,
            houzhui: (result.fileName + '').substring((result.fileName + '').lastIndexOf('.') + 1)
          }
          console.log('🚩 this.file: ', this.file)
        }
        Object.keys(this.formData).forEach(key => {
          if (key == 'enabled') {
            this.formData[key] = result[key]
          } else {
            // this.formData[key] = data[key] + '' && data[key] + '' !== 'null' ? data[key] + '' : ''
            this.formData[key] = result[key]
          }
        })
      } else {
      }
    },

    // 时间控件
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
    },

    // 上传前
    handleBeforeUpload (file) {
      this.file = file
      // this.formData.fileName = file.name
      console.log('file: ', this.file)
      this.isCanDownload = false
      return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.code === 200 && res.success) {
        this.$Message.success(res.message)
        this.isShowCreateEnterpriseCertificateModal = false
      } else {
        this.isCanSubmit = true
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
        this.isShowCreateEnterpriseCertificateModal = true
      }
      this.$emit('query')
    },

    // 确定导入
    handleSubmitBatchImport () {
      this.isCanSubmit = false

      console.log('this.$refs.upload: ', this.$refs.upload)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.formData.fileName = this.file
          this.formData.startTime = this.$moment(this.formData.startTime).format('YYYY-MM-DD')
          this.formData.endTime = this.$moment(this.formData.endTime).format('YYYY-MM-DD')
          console.log('this.formData: ', this.formData)
          console.log('this.file: ', this.file)

          this.$refs.upload[0].post(this.formData)
        } else {
          this.$Message.warning('输入有误，请返回检查!')
          this.isCanSubmit = true
        }
      })
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 图片预览
    previewImg (url) {
      this.isPreviewImgModal = true
      this.currentPreviewImg = url
    }
  }
}
</script>

<style lang="less" scoped>

</style>
